<?php
namespace App\Services;


use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class OpenImService {

    private static function commonRequest($path, $data, $method = "POST", $token = true)
    {
        if(strpos($path, 'http') === false) {
            $host = config('services.open_im.url');
            $url = $host . $path;
        } else {
            $url = $path;
        }

        $header = [
            'operationID' => (string) Carbon::now()->valueOf()
        ];

        if($token) {
            $header['token'] = self::getAppToken();
        }

        if($method == "POST") {
            $response = Http::retry(3, 1000)
                -> timeout(5)
                -> withHeaders($header)
                -> post($url, $data)
                -> throw()
                -> json();
        } else {
            $response = Http::retry(3, 1000)
                -> timeout(5)
                -> withHeaders($header)
                -> get($url, $data)
                -> throw()
                -> json();
        }
        if(!$response) {
            Log::error('请求失败', $response);
            throw new AccessDeniedHttpException('IM服务请求失败');
        }

        if($response['errCode'] != 0) {
            Log::error('操作失败', $response);
            throw new AccessDeniedHttpException($response['errMsg']);
        }

        return $response;
    }

    private static function getAppToken() {
        $token = Cache::has('open_id_app_token');

        if($token) {
            return Cache::get('open_id_app_token');
        }

        $path = "/auth/get_admin_token";

        $data = [
          "secret" => config('services.open_im.secret'),
          "userID" => config('services.open_im.app_user_id'),
        ];

        $res = self::commonRequest($path, $data,'POST',false);

        Cache::put('open_id_app_token', $res['data']['token'], $res['data']['expireTimeSeconds'] - 60 );

        return $res['data']['token'];
    }

    public static function initUser(array $users) {
        $path = "/user/user_register";

        $data = [];

        $ids = self::getAllUserIds();

        foreach($users as $user) {
            if(in_array($user['id'], $ids['data']['userIDs'])) {
                continue;
            }

            $data['users'][] = [
                "userID"   => (string) $user['id'],
                "nickname" => $user['name'],
                "faceURL"  => ""
            ];
        }

        $res = self::commonRequest($path, $data);

        return $res;
    }

    public static function getUserToken($user_id)
    {
        $path = "/auth/get_user_token";

        $data = [
            'platformID' => 2,
            'userID'     => (string) $user_id
        ];

        $res = self::commonRequest($path, $data);

        return $res;
    }

    public static function getUserTokenOnline($user_id)
    {
        $path = "/user/get_users_online_status";

        $data = [
            'userIDs' => [(string) $user_id]
        ];

        $res = self::commonRequest($path, $data);

        return $res;
    }

    public static function getAllUserIds()
    {
        $path = "/user/get_all_users_uid";

        $data = [
            'pagination' => [
                'pageNumber' => 1,
                'showNumber' => 100
            ]
        ];

        $res = self::commonRequest($path, $data);

        return $res;
    }
}
